#include <string>
#include <time.h>
#include <stdlib.h>
#include "TestRules.h"
#include "../Model/GameModel.h"
#include "../Interface/Player.h"
#include "../Connector/Connector.h"

int TestRules::commonDuelTestNum_ = 1000;

void TestRules::testCommonDuel()
{
  for (int count = 0; count != commonDuelTestNum_; ++count)
  {
    int playersNum = 3;
    GameModel model;
    Connector connector(model);
    Player players[playersNum];
    std::string name = "";
    int error = 0;
    time_t connectTime = time(0);
    for (int i = 0; i != playersNum; ++i)
    {
      players[i].setConnector(connector);
      players[i].connect(name, connectTime, error);
    }
    connector.startGame();

    srand(time(0));
    int i = 0;
    bool exit = false;
    int arrowsInsideCount = 0;
    while (model.isGameStarted())
    {
      if (model.getArrowsInsideFlag() != 0)
      {
        players[i].getTotem();
      }
      players[i].openCard();
      for (int j = 0; j != playersNum; j++)
      {
        for (int k = 0; k != playersNum; k++)
        {
          if ((j != k) &&
              (model.getTopCardID(players[j].getSeat()) != -1) &&
              (model.getTopCardID(players[j].getSeat()) == (model.getTopCardID(players[k].getSeat()))))
          {
            int a = rand() % 2;
            int b = 0;
            if (a == 0)
            {
              a = j;
              b = k;
            }
            else
            {
              a = k;
              b = j;
            }
            int opened0 = model.getOpenedCardsNumber(0);
            int closed1 = model.getClosedCardsNumber(players[a].getSeat());
            int closed2 = model.getClosedCardsNumber(players[b].getSeat());
            int opened1 = model.getOpenedCardsNumber(players[a].getSeat());
            int opened2 = model.getOpenedCardsNumber(players[b].getSeat());
            players[a].getTotem();;
            bool check = ((model.getOpenedCardsNumber(players[a].getSeat()) == 0) &&
                         (model.getClosedCardsNumber(players[b].getSeat()) == closed2 + opened1 + opened2 +
                                                                              opened0));
            showError(check);
            checkError(check);
            exit = true;
            break;
          }
        }
        if (exit)
        {
          break;
        }
      }
      if (exit)
      {
        break;
      }
      ++i;
      i = i % playersNum;
    }
  }
  return;
}

void TestRules::test()
{
  testCommonDuel();
}


